package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.dialog.PopupWindowUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.app.DemoContext;
import io.rong.app.RongCloudEvent;
import io.rong.app.activity.FriendListActivity;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.model.Event;
import io.rong.imlib.RongIMClient;

@SuppressLint("CommitPrefEdits")
public class MessageFragment extends BaseNavItemFragment {

    private static final String ARGS_MAIN_DATA = "com.enterplorer.args.main.data";

    private Context mContext;

    @Bind(R.id.tv_company_name)
    protected TextView tvCompanyName;
    @Bind(R.id.iv_right_icon)
    protected ImageView ivRightIcon;
    @Bind(R.id.title_bar_content)
    protected RelativeLayout rlTitleContent;
    @Bind(R.id.rl_msg_loading)
    protected RelativeLayout rlLoading;

    private MainExtraBean mMainExtraBean;
    private SharedPreferences mPreferences;

    private Disposable mDisposable;

    public static MessageFragment newInstance(MainExtraBean mainExtraBean) {
        MessageFragment messageFragment = new MessageFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_MAIN_DATA, mainExtraBean);
        messageFragment.setArguments(bundle);
        return messageFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        this.mPreferences = YspPreferences.getInstance().getSharedPreferences();
        this.mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_MAIN_DATA);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rlTitleContent.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        if (mMainExtraBean == null) {
            mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_MAIN_DATA);
        }
        tvCompanyName.setText("消息中心");
        ivRightIcon.setImageResource(R.drawable.add_groupchat);
        ivRightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindowUtil.showIMPlusPopup(v, createGroupListener, massTextListener);
            }
        });
        if (savedInstanceState != null) {
            Fragment fragment = getChildFragmentManager().findFragmentByTag(ConversationListFragment.class.getName());
            if (fragment != null) {
                FragmentManager fm = getChildFragmentManager();
                fm.beginTransaction().remove(fragment).commit();
                fm.executePendingTransactions();
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //开始链接融云，all接口和群组数据接口
        final UserInfo userInfo = mMainExtraBean.getUserInfo();
        final String uuid = userInfo.getUuid();
        String userName = userInfo.getName();
        String userAvatar = userInfo.getAvatar();
        String companyId = userInfo.getCompanyId();
        String password = userInfo.getPassword();
        RongContext.getInstance().setCurrentUserInfo(new io.rong.imlib.model.UserInfo(uuid, userName, TextUtils.isEmpty(userAvatar) ? null : Uri.parse(userAvatar)));
        final DatabaseUtil databaseUtil = new DatabaseUtil();
        YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_USER_INFO, StringUtilSub.base64(userInfo)).apply(); //IM相关某些页面需要使用
        mDisposable = HttpMethods.getInstance().allContacts(companyId, uuid, password).flatMap(new Function<List<UserInfo>, Publisher<List<GroupCreateInfo>>>() {
            @Override
            public Publisher<List<GroupCreateInfo>> apply(List<UserInfo> userInfos) throws Exception {
                databaseUtil.InsertAllUser(userInfos);
                return HttpMethods.getInstance().allGroups(uuid);
            }
        }).flatMap(new Function<List<GroupCreateInfo>, Publisher<List<GroupCreateInfo>>>() {
            @Override
            public Publisher<List<GroupCreateInfo>> apply(List<GroupCreateInfo> groupInfos) throws Exception {
                databaseUtil.resetGroupsTable(groupInfos);
                return Flowable.just(groupInfos);
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<GroupCreateInfo>>() {
            @Override
            public void accept(List<GroupCreateInfo> groupCreateInfos) throws Exception {
                DemoContext.getInstance(mContext).setResult(groupCreateInfos);
                connectIM(mMainExtraBean.getToken(), uuid);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
                connectIM(mMainExtraBean.getToken(), uuid);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    private int tokenIncorrectCount = 0;

    private void connectIM(String token, final String uuid) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            @Override
            public void onTokenIncorrect() {
                if (tokenIncorrectCount < 3) {
                    //刷新Token
                    HttpMethods.getInstance().reFetchToken(uuid, new EnterBaseSubscriber() {
                        @Override
                        public void onSuccess(JSONObject data) {
                            String newToken = data.optString("token");
                            if (!TextUtils.isEmpty(newToken)) {
                                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_TOKEN, newToken).apply();
                                connectIM(newToken, uuid);
                            } else {
                                onFailure("token为空");
                            }
                        }

                        @Override
                        public void onFailure(String errorMessage) {
                        }
                    });
                    tokenIncorrectCount++;
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {
                attachConversationFragment();
            }

            @Override
            public void onSuccess(String arg0) {
                YspPreferences.getInstance().getSharedPreferences().edit().putBoolean("RCSconnectStatus", true).apply();
                RongCloudEvent.getInstance().setOtherListener();
                EventBus.getDefault().post(new YspEvent.ConnectEvent());
                RongContext.getInstance().getEventBus().post(Event.ConnectEvent.obtain(true));
                attachConversationFragment();
            }
        });
    }

    private void attachConversationFragment() {
        rlLoading.setVisibility(View.GONE);
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fl_conversion_content);
        ConversationListFragment conversationListFragment;
        if (fragment != null) {
            conversationListFragment = (ConversationListFragment) fragment;
            transaction.show(conversationListFragment).commitAllowingStateLoss();
        } else {
            conversationListFragment = YspConversationListFragment.newInstance(mContext);
            transaction.replace(R.id.fl_conversion_content, conversationListFragment, ConversationListFragment.class.getName()).commitAllowingStateLoss();
        }
    }

    private PopupWindowUtil.CreateGroupListener createGroupListener = new PopupWindowUtil.CreateGroupListener() {
        @Override
        public void onClick(View view) {
            if (mPreferences.getBoolean("RCSconnectStatus", false)) {
                //状态码   创建群
                startIntent(1);
            } else {
                Toast.makeText(mContext, "IM功能不可用", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private PopupWindowUtil.MassTextListener massTextListener = new PopupWindowUtil.MassTextListener() {
        @Override
        public void onClick(View view) {
            //状态码    短信群发
            startIntent(4);
        }
    };

    public void startIntent(int state) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(FriendListActivity.STATE, state);
        intent.putExtra(FriendListActivity.FROMHERE, bundle);
        intent.setClass(mContext, FriendListActivity.class);
        startActivity(intent);
    }

    //根据显示的状态改变 判断是否进行Notification提示
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Globals.MESSAGE_FRAGMENT_STATUS = 0;
        } else {
            Globals.MESSAGE_FRAGMENT_STATUS = 1;
        }
    }

    //当按了home键的时候 将framgment的状态改变为隐藏
    @Override
    public void onPause() {
        super.onPause();
        Globals.MESSAGE_FRAGMENT_STATUS = 0;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (this.isHidden()) {
            Globals.MESSAGE_FRAGMENT_STATUS = 0;
        } else {
            Globals.MESSAGE_FRAGMENT_STATUS = 1;
        }
    }
}
